package com.twu.biblioteca;

import java.io.InputStream;
import java.util.Scanner;

class InputDispatcher implements Runnable {

    private final InputStream inputStream;

    private final Handler handler;

    InputDispatcher(InputStream inputStream, Handler handler) {
        this.inputStream = inputStream;
        this.handler = handler;
    }

    void init() {
        handler.init();
    }

    @Override
    public void run() {
        try (Scanner scanner = new Scanner(inputStream)) {
            while (handler.isClosed() == false && scanner.hasNextLine()) {
                String input = scanner.nextLine();
                handler.handle(input);
            }
        }
    }

    interface Handler {

        void init();

        void handle(String input);

        boolean isClosed();

    }

}
